﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ch.Elca.Iiop;
using Ch.Elca.Iiop.Idl;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.IO;
using System.ComponentModel;
using System.Windows;

namespace ModelicaNet
{
    [RepositoryID( "IDL:OmcCommunication:1.0" )]
    public interface IOmcCommunication
    {

        [return: StringValue]
        [return: WideChar( false )]
        string sendExpression( [StringValue][WideChar( false )] string expr );

        [return: StringValue]
        [return: WideChar( false )]
        string sendClass( [StringValue][WideChar( false )] string model );
    };

    public static class OmcConnection
    {
        static private IOmcCommunication omcCommunication = null;

        static OmcConnection() {
            ChannelServices.RegisterChannel( new IiopClientChannel(), false );
        }

        static private void Connect() {            
            string idFile = Path.GetTempPath() + "openmodelica.objid";
            string ior;
            try {
                ior = File.ReadAllText( idFile ).Trim();                
            }
            catch (Exception e) {
                throw new Exception( "OpenModelica compiler (omc.exe) is not running or the objid file cannot be read:\n '" 
                                     + idFile + "'. ", e );                                              
            }
            try {
                omcCommunication = (IOmcCommunication) RemotingServices.Connect( typeof( IOmcCommunication ), ior );
            }
            catch (Exception e) {
                throw new Exception("Cannot connect to OpenModelica compiler:\n" + e.Message, e);
            }
        }
        public static string SendClass( string model ) {
            if( omcCommunication == null )
                Connect();
            try {
                return omcCommunication.sendClass( model );
            }
            catch( Exception e ) {
                omcCommunication = null;
                throw new Exception( "Cannot send message >>" + model + "<< to OpenModelica compiler:\n" + e.Message, e);
            }
        }
    }    
}
